package com.cb.spzx.manager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cb.spzx.manager.service.SysMenuService;
import com.cb.spzx.model.dto.system.AssginMenuDto;
import com.cb.spzx.model.entity.system.SysMenu;
import com.cb.spzx.model.entity.system.SysRoleMenu;
import com.cb.spzx.manager.service.SysRoleMenuService;
import com.cb.spzx.manager.mapper.SysRoleMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
* @author lenovo
* @description 针对表【sys_role_menu(角色菜单)】的数据库操作Service实现
* @createDate 2024-04-11 16:57:26
*/
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService{
    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public Map<String, Object> findSysRoleMenuByRoleId(Long roleId) {
        // 查询所有的菜单数据
        List<SysMenu> menuList = sysMenuService.findNodes();
        // 查询当前角色的菜单数据
        LambdaQueryWrapper<SysRoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleMenu::getRoleId,roleId).eq(SysRoleMenu::getIsHalf,0);
        List<SysRoleMenu> sysRoleMenus = baseMapper.selectList(queryWrapper);
        List<Long> menuIds=new ArrayList<>();
        for (SysRoleMenu menu : sysRoleMenus) {
            menuIds.add(menu.getMenuId());
        }
        // 将数据存储到Map中进行返回
        Map<String,Object> map=new HashMap<>();
        map.put("sysMenuList",menuList);
        map.put("roleMenuIds",menuIds);
        return map;
    }

    @Override
    public void doAssign(AssginMenuDto assginMenuDto) {
        // 根据角色的id删除其所对应的菜单数据
        LambdaQueryWrapper<SysRoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleMenu::getRoleId,assginMenuDto.getRoleId());
        Long count = baseMapper.selectCount(queryWrapper);
        if(count!=0){
            baseMapper.delete(queryWrapper);
        }
        //保存分配数据
        List<Map<String, Long>> menuIdList = assginMenuDto.getMenuIdList();
        System.out.println(menuIdList);
        if(menuIdList!=null && menuIdList.size()>0){
            Long roleId = assginMenuDto.getRoleId();
            for (Map<String, Long> map : menuIdList) {
                System.out.println(map);
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setRoleId(roleId);
                sysRoleMenu.setMenuId(map.get("id"));
                sysRoleMenu.setIsHalf(Math.toIntExact(map.get("isHalf")));
                sysRoleMenu.setCreateTime(new Date());
                sysRoleMenu.setUpdateTime(new Date());
                System.out.println(sysRoleMenu);
                baseMapper.insert(sysRoleMenu);
            }
        }
    }
}




